import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Radio,
  Select,
  Icon,
  Button,
  Upload,
  List,
  Modal,
  message,
  Badge,
  TreeSelect,
  Tag,
  InputNumber,
} from 'antd';
import ListForm from './ListForm';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './ContentEdit.less';
import ChooseAuthorModal from 'components/Content/ChooseAuthorModal';
import ChooseTagModal from 'components/Content/ChooseTagModal';

import { routerRedux } from 'dva/router';
import { imgPrex } from '../../utils/constData';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const { Option } = Select;
const { CheckableTag } = Tag;

const formItemLayout1 = {
  labelCol: {
    xs: { span: 14 },
    sm: { span: 2 },
    md: { span: 2 },
    lg: { span: 2 },
  },
  wrapperCol: {
    xs: { span: 8 },
    sm: { span: 8 },
    md: { span: 8 },
    lg: { span: 8 },
  },
};

const formItemLayout = { labelCol: { span: 2 }, wrapperCol: { span: 15 } }

const priceItemLayout = {
  labelCol: {
    xs: { span: 12 },
    sm: { span: 8 },
    md: { span: 8 },
    lg: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 14 },
    sm: { span: 9 },
    md: { span: 9 },
    lg: { span: 9 },
  },
};

const tailFormItemLayout = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 16, offset: 2 },
  },
};

const CreateBookletForm = Form.create()(props => {
  const { modalVisible, form, handleSave, handleModalVisible, title, bookletRecord, bookletUploadProps, bookletFileList, bookletModalVisible, bookletOk } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      bookletOk(false, fieldsValue);
    });
  };

  return (
    <Modal
      destroyOnClose
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => bookletModalVisible(false)}
    >
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="封面">
        {
          form.getFieldDecorator('name', {
            // valuePropName: 'fileList',
            rules: [{ required: true, message: '请选择封面' }],
            initialValue: bookletRecord ? (<img src={imgPrex + bookletRecord.bookletImg} style={{ width: 30, height: 30 }} />) : null,
          })
            (<Upload
              {...bookletUploadProps}
            >
              <Button>
                <Icon type="upload" />浏览
         			  </Button>
            </Upload>)}
        {(bookletRecord && bookletRecord.bookletImg && !(bookletFileList && (bookletFileList.length > 0))) ?
          <img src={imgPrex + bookletRecord.bookletImg} style={{ width: 50 }} />
          :
          null
        }
      </FormItem>
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="序号" style={{ display: 'none' }}>
        {form.getFieldDecorator('bookletSeq', {
          initialValue: bookletRecord ? bookletRecord.bookletSeq : 1,
          rules: [{ required: true, message: '请输入名称' }],
        })(<Input placeholder="请输入名称" maxLength="10" />)}
      </FormItem>
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="名称">
        {form.getFieldDecorator('bookletName', {
          initialValue: bookletRecord ? bookletRecord.bookletName : 1,
          rules: [{ required: true, message: '请输入名称' }],
        })(<Input placeholder="请输入名称" maxLength="10" />)}
      </FormItem>
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="链接">
        {form.getFieldDecorator('bookletUrl', {
          initialValue: bookletRecord ? bookletRecord.bookletUrl : null,
          rules: [{ required: true, message: '请输入链接' }],
        })(<Input placeholder="请输入链接" maxLength="200" />)}
      </FormItem>
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="视频ID">
        {form.getFieldDecorator('videoId', {
          initialValue: bookletRecord ? bookletRecord.videoId : null,
          rules: [{ required: true, message: '请输入视频ID' }],
        })(<Input placeholder="请输入视频ID" maxLength="20" />)}
      </FormItem>
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="第三方ID">
        {form.getFieldDecorator('thirdPartyId', {
          initialValue: bookletRecord ? bookletRecord.thirdPartyId : null,
          rules: [{ required: true, message: '请输入视频ID' }],
        })(<Input placeholder="请输入视频ID" maxLength="20" />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ content, loading }) => ({
  content,
  channelTree: content.channelTree,
  tagList: content.tagList,
  authorList: content.authorList,
  goodsDetail: content.goodsDetail,
  loading: loading.models.content,
}))
@Form.create()
export default class ContentAdd extends PureComponent {
  state = {
    authorModalVisible: false,
    tagModalVisible: false,
    bookletFormVisible: false,
    fileList: [],
    file: null,
    image: null,

    bookletFileList: [],
    bookletFile: null,
    bookletImage: null,

    bookletList: [{
      bookletSeq: 1,
      name: null,
      "bookletUnit": "集",
      "bookletName": '第' + 1 + '集',
      "bookletUrl": null,
      "bookletType": 1,
      "durationTime": 1000,
      "isFree": 1,
      "vedioId": null,
      "thirdPartyId": null,
    }],

    bookletRecord: null,


  };

  componentDidMount() {
    console.log('上个页面传的参数', this.props.match.params.goodsId)
    this.props.dispatch({
      type: 'content/fetchAuthorList',
      payload: { pageNum: 1, pageSize: 0 },
    });

    this.props.dispatch({
      type: 'content/fetchGoodsDetail',
      payload: { goodsId: this.props.match.params.goodsId },
      callback: (data) => this._setGoodsDetail(data)
    });

    this.props.dispatch({
      type: 'content/fetchChannelTree',
      payload: {},
    });

    this.props.dispatch({
      type: 'content/fetchTagList',
      payload: { labelType: 1 },
    });


  }

  _setGoodsDetail(data) {
    let authorName = null;
    for (let i = 0; i < this.props.authorList.length; i++) {
      if (this.props.authorList[i].authorId == data.authorId) {
        authorName = this.props.authorList[i].authorName
      }
    }
    let newData = { ...data, authorName: authorName }

    console.log('newDatanewDatanewDatanewData', newData)

    this.setState({
      bookletRecord: newData
    })
  }

  handleAppChange = e => { };

  handleAuthorModalVisible = flag => {
    this.setState({ authorFormVisible: !!flag });
  };



  checkOriginalPrice = (rule, value, callback) => {
    const { getFieldValue } = this.props.form
    if (value && value < getFieldValue('discountPrice')) {
      callback('原价不能小于售价！')
    }

    // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
    callback()
  }

  submit() {
    console.log('this.props.form=====', this.state.bookletList)
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;

      let bookletList = this.state.bookletList;
      for (let i = 0; i < bookletList.length; i++) {
        let one = bookletList[i];
        if (!one.name) {
          message.error(one.bookletName + '信息不完善，请填写该册信息')
          return;
        }
        if (!one.bookletSeq) {
          message.error(one.bookletName + '信息不完善，请填写该册信息')
          return;
        }
        if (!one.bookletName) {
          message.error(one.bookletName + '信息不完善，请填写该册信息')
          return;
        }
        if (!one.bookletUrl) {
          message.error(one.bookletName + '信息不完善，请填写该册信息')
          return;
        }
        if (!one.videoId) {
          message.error(one.bookletName + '信息不完善，请填写该册信息')
          return;
        }
        if (!one.thirdPartyId) {
          message.error(one.bookletName + '信息不完善，请填写该册信息')
          return;
        }

      }

      console.log('表单提交图片：：：：？？？', this.state.file)
      console.log('册集信息：：：：？？？', this.state.bookletList)

      let tags = fieldsValue.labelList;
      let newTags = [];
      if (tags) {
        for (let i = 0; i < tags.length; i++) {
          newTags.push({ labelId: tags[i].labelId })
        }
      }

      let values = { ...fieldsValue, name: this.state.file, labelList: newTags }
      console.log('表单提交数据：：：：？？？', values)
      this.props.form.resetFields();
      this.props.dispatch({
        type: 'content/editContent',
        payload: values,
        bookletList: this.state.bookletList,
        callback: () => this._callback()
      });
    });
  }

  _callback() {
    this.props.dispatch(routerRedux.goBack())
  }

  onChange() {

  }

  _setAuthorModalVisible(flag) {
    if (!flag) {
      this.setState({

      })
    }
    this.setState({ authorModalVisible: flag })
  }

  _authorSearch(search) {
    console.log('search', search)
    this.props.dispatch({
      type: 'content/fetchAuthorList',
      payload: { authorName: search, pageNum: 1, pageSize: 0 },
    });
  }

  _chooseAuthor(author) {
    console.log('_chooseAuthor', author)
    this.props.form.setFieldsValue({ authorId: author.authorId, authorName: author.authorName })
    this._setAuthorModalVisible(false)
    console.log(this.props.form.getFieldValue('authorId'))
  }

  _setTagModalVisible(flag) {
    if (!flag) {
      this.props.dispatch({
        type: 'content/fetchTagList',
        payload: { labelType: 1 },
      });
    }
    this.setState({ tagModalVisible: flag })
  }

  _tagSearch(search) {
    console.log('search', search)
    this.props.dispatch({
      type: 'content/fetchTagList',
      payload: { labelName: search, "labelType": 1 },
    });
  }

  _chooseTags(tags) {
    console.log('_chooseTags', tags)
    this.props.form.setFieldsValue({ labelList: tags })
    this._setTagModalVisible(false)
    console.log(this.props.form.getFieldValue('labelList'))
  }

  _deleteTag(deleteTag) {
    console.log('delete tag', deleteTag);

    const newLabelList = this.props.form.getFieldValue('labelList').filter(tag => tag !== deleteTag)
    console.log('newLabelList', newLabelList)
    this.props.form.setFieldsValue({ labelList: newLabelList })
  }

  _bookletAmount(amount) {
    let newBookletList = [];
    if (amount && amount > 0) {
      for (let i = 1; i < (amount + 1); i++) {
        newBookletList.push(
          {
            bookletSeq: i,
            title: '第' + i + '集',
            name: null,
            "bookletUnit": "集",
            "bookletName": '第' + i + '集',
            "bookletUrl": "",
            "bookletType": 1,
            "durationTime": 1000,
            "isFree": 1,
            "vedioId": "",
            "thirdPartyId": ""
          }
        )
      }
    }
    this.setState({ bookletList: newBookletList })
  }

  _bookletModalVisible(flag, item) {
    console.log('item bookletrecord', item)
    if (!flag) {
      this.setState({
        childRecord: null,
        bookletFormVisible: flag,

        bookletFileList: [],
        bookletfile: null,
      })
    } else {
      this.setState({
        childRecord: item,
        bookletFormVisible: flag,
      })
    }
  }

  _bookletOk(flag, booklet) {
    console.log(this.state.bookletFile);
    let newBooklet = { ...booklet, name: this.state.bookletFile, "bookletType": 1, "durationTime": 1000, "isFree": 1, bookletUnit: '集', }
    this._bookletModalVisible(flag);
    let newBookletList = this.state.bookletList;
    newBookletList.splice((booklet.bookletSeq - 1), 1, newBooklet);
    console.log(newBookletList)
  }

  render() {
    const { form } = this.props;
    const { authorFormVisible, bookletFormVisible } = this.state;
    const authorParentMethods = {
      handleModalVisible: this.handleAuthorModalVisible,
    };
    const bookletParentMethods = {
      handleModalVisible: this.handleBookletModalVisible,
    };

    const uploadProps = {
      // action: '//jsonplaceholder.typicode.com/posts/',
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        console.log('file======', file)
        this.setState(({ fileList }) => ({
          fileList: [file],
          file: file,
          image: null,
        }));
        this.props.form.setFieldsValue({
          name: file
        });
        return false;
      },
      fileList: this.state.fileList
    };

    const bookletUploadProps = {
      // action: '//jsonplaceholder.typicode.com/posts/',
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            bookletFileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(({ fileList }) => ({
          bookletFileList: [file],
          bookletFile: file,
          bookletImage: null,
        }));

        return false;
      },
      fileList: this.state.bookletFileList
    };


    return (
      <PageHeaderLayout title="">
        <Card>
          <Form onSubmit={() => this.submit()} >
            <FormItem {...formItemLayout} label="名称" style={{ display: 'none' }}>
              {form.getFieldDecorator('goodsId', {
                rules: [{ required: true, message: '请输入名称' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.goodsId : null,
              })(<Input placeholder="请输入名称" />)}
            </FormItem>

            <FormItem {...formItemLayout} label="APP">
              {form.getFieldDecorator('appType', {
                rules: [{ required: true, message: '请选择APP类型' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.appType : "1",
              })(
                <RadioGroup onChange={this.handleAppChange}>
                  <RadioButton value="1">小萌早教</RadioButton>
                  <RadioButton value="2">小萌绘本</RadioButton>
                  <RadioButton value="3">萌萌乐卡通</RadioButton>
                  <RadioButton value="4">萌萌乐儿歌</RadioButton>
                </RadioGroup>
              )}

            </FormItem>
            <FormItem {...formItemLayout} label="频道">
              {form.getFieldDecorator('channelId', {
                rules: [{ required: true, message: '请选择频道' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.channelId : null,
              })(<TreeSelect
                // style={{ width: 300 }}
                // value={this.state.value}
                dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                treeData={this.props.channelTree}
                placeholder="请选择"
                treeDefaultExpandAll
                onChange={this.onChange}
              />)}
            </FormItem>

            <FormItem {...formItemLayout} label="封面">
              {form.getFieldDecorator('name', {
                rules: [{ required: true, message: '请选择封面' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.goodsImg : null,
              })(<Upload {...uploadProps}>
                {(this.state.bookletRecord && !(this.state.fileList && (this.state.fileList.length > 0))) ?
                  <img src={imgPrex + this.state.bookletRecord.goodsImg} style={{ width: 50 }} />
                  :
                  null
                }
                <Button style={{ marginLeft: '10px' }}>
                  <Icon type="upload" />浏览
              </Button>

              </Upload>)}

            </FormItem>

            <FormItem {...formItemLayout} label="名称">
              {form.getFieldDecorator('goodsName', {
                rules: [{ required: true, message: '请输入名称' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.goodsName : null,
              })(<Input placeholder="请输入名称" />)}
            </FormItem>

            <FormItem {...formItemLayout} label="作者">
              {form.getFieldDecorator('authorName', {
                rules: [{ required: true, message: '请选择作者' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.authorName : null,
              })(
                <span>
                  <Input style={{ width: '83%' }} value={this.props.form.getFieldValue('authorName')} disabled />
                  <Button
                    onClick={() => {
                      this._setAuthorModalVisible(true);
                    }}>
                    选择
              </Button>
                </span>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="作者ID" style={{ display: 'none' }}>
              {form.getFieldDecorator('authorId', {
                rules: [{ required: true, message: '请输入名称' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.authorId : null,
              })(
                <span>
                  {this.props.form.getFieldValue('authorId')}
                </span>
              )}
            </FormItem>

            <Row type="flex" justify="start">
              <Col span={6}>
                <FormItem {...priceItemLayout} label="售价">
                  {form.getFieldDecorator('discountPrice', {
                    rules: [{ required: true, message: '请输入售价' }],
                    initialValue: this.state.bookletRecord ? this.state.bookletRecord.discountPrice : null,
                  })(<InputNumber min={0} step={1.0} precision={2} placeholder="" style={{ width: '100%' }} />)}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem {...priceItemLayout} label="原价">
                  {form.getFieldDecorator('originalPrice', {
                    rules: [{
                      validator: this.checkOriginalPrice
                    }],
                    initialValue: this.state.bookletRecord ? this.state.bookletRecord.discountPrice : null,
                  })(<InputNumber min={0} step={1.0} precision={2} placeholder="" style={{ width: '100%' }} />)}
                </FormItem>
              </Col>

            </Row>

            <FormItem {...formItemLayout} label="状态">
              {form.getFieldDecorator('goodsSts', {
                rules: [{ required: true, message: '请选择内容状态' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.goodsSts : "1",
              })(
                <RadioGroup>
                  <RadioButton value="1">上架</RadioButton>
                  <RadioButton value="2">下架</RadioButton>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="标签">
              {form.getFieldDecorator('labelList', {
                rules: [{ required: true, message: '添加标签' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.labelList : [],
              })(
                <span></span>
                // this.props.form.getFieldValue('labelList') ? this.props.form.getFieldValue('labelList').map(
                //   (item, i) => <Tag closable={true} afterClose={() => this._deleteTag(tag)}>Tag 1</Tag>
                // )
                //   : []
              )}

              {
                this.props.form.getFieldValue('labelList') ? this.props.form.getFieldValue('labelList').map(
                  (item, i) => <Button style={{ marginLeft: '5px' }} icon="delete" type={"primary"} title={"点击删除"} key={i} onClick={() => this._deleteTag(item)}>{item.labelName}</Button>
                )
                  : null
              }
              <Button icon="plus"
                style={{ marginLeft: '5px' }}
                type={"dashed"}
                onClick={() => {
                  this._setTagModalVisible(true);
                }}>
                添加标签
              </Button>
            </FormItem>
            <FormItem {...formItemLayout} label="权重">
              {form.getFieldDecorator('weight', {
                rules: [{ required: true, message: '请输入权重' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.bookletCount : null,
              })(<InputNumber min={0} step={1} placeholder="请输入权重" style={{ width: '100%' }} />)}
            </FormItem>

            <FormItem {...formItemLayout} label="集数">
              {form.getFieldDecorator('amount', {
                rules: [{ required: true, message: '请输入集数' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.discountPrice : 1,
              })(<InputNumber min={1} step={1} placeholder="请输入集数" style={{ width: '100%' }} onChange={(value) => this._bookletAmount(value)} />)}
            </FormItem>

            <FormItem {...formItemLayout} label="简称">
              {form.getFieldDecorator('goodsAbrv', {
                rules: [{ required: true, message: '请输入商品简称' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.goodsAbrv : null,
              })(<Input placeholder="请输入商品简称" />)}
            </FormItem>

            <FormItem {...formItemLayout} label="简介">
              {form.getFieldDecorator('goodsIntr', {
                rules: [{ required: true, message: '请输入商品简介' }],
                initialValue: this.state.bookletRecord ? this.state.bookletRecord.goodsIntr : null,
              })(<Input placeholder="请输入商品简介" />)}
            </FormItem>

            <FormItem {...tailFormItemLayout}>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button type="danger" onClick={() => { this.props.dispatch(routerRedux.push({ pathname: '/content/conntent' })); }} style={{ marginLeft: '15px' }}>
                返回列表
              </Button>
            </FormItem>

          </Form>
        </Card>

        <Card>
          <List rowKey="bookletSeq" grid={{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 2, xl: 4, xxl: 6 }}>
            {this.state.bookletRecord && (this.state.bookletRecord.bookletList && (this.state.bookletRecord.bookletList.length > 0))
              && this.state.bookletRecord.bookletList.map((item, i) => {
                return (
                  <List.Item key={item.bookletSeq} >
                    <Card style={{ marginLeft: '10px' }}
                      title={'第' + item.bookletSeq + '集'}
                      style={{ width: 220 }}
                      cover={
                        <img style={{ height: '120px' }}
                          alt="example"
                          src={imgPrex + item.bookletImg}
                        />
                      }
                      actions={[
                        <Button
                          icon="edit"
                          size="large"
                          onClick={() => {
                            this._bookletModalVisible(true, item);
                          }}
                        >
                          编辑
                </Button>,
                      ]}
                    >
                      <Card.Meta title={'链接：' + item.bookletUrl ? item.bookletUrl : '请填写'} />
                    </Card>
                  </List.Item>
                )
              })}
          </List>
        </Card>
        {/* <CreateAuthorForm
          title="选择作者"
          {...authorParentMethods}
          modalVisible={authorFormVisible}
        /> */}
        <ChooseAuthorModal visible={this.state.authorModalVisible} authorList={this.props.content.authorList}
          setAuthorVisible={(flag) => this._setAuthorModalVisible(flag)} authorId={this.props.form.getFieldValue('authorId') && this.props.form.getFieldValue('authorId')}
          authorSearch={(search) => { this._authorSearch(search) }} chooseAuthor={(author) => this._chooseAuthor(author)}
        />

        <ChooseTagModal visible={this.state.tagModalVisible} tagList={this.props.content.tagList} checkedTags={this.props.form.getFieldValue('labelList')}
          setTagVisible={(flag) => this._setTagModalVisible(flag)}
          tagSearch={(search) => { this._tagSearch(search) }} chooseTags={(tags) => this._chooseTags(tags)}
        />

        <CreateBookletForm
          title={(this.props.form.getFieldValue('goodsName') ? this.props.form.getFieldValue('goodsName') : '') + (this.state.bookletRecord ? '      第' + this.state.bookletRecord.bookletSeq + '集' : null)}
          bookletModalVisible={(flag) => this._bookletModalVisible(flag)}
          bookletOk={(flag, booklet) => this._bookletOk(flag, booklet)}
          bookletUploadProps={bookletUploadProps}
          bookletRecord={this.state.bookletRecord}
          modalVisible={bookletFormVisible}
          bookletFileList={this.state.bookletFileList}
        />
      </PageHeaderLayout>
    );
  }
}
